package com.mediacloud.app.newsmodule.fragment.videomonitor.vod;

import android.app.Activity;
import android.content.Context;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;

import com.mediacloud.app.cloud.ijkplayersdk.auth.URLAuth;

import com.mediacloud.app.newsmodule.drama.DramaDetailActivity;
import com.tencent.liteav.demo.superplayer.model.entity.ChildDto;
import com.tencent.liteav.demo.superplayer.model.entity.MovieBean;
import com.tencent.liteav.demo.superplayer.model.entity.MovieBeannew;
import com.tencent.liteav.demo.superplayer.model.entity.ProgramSimpleBean;
import com.mediacloud.app.newsmodule.fragment.baoliao.model.DramaDetailResponse;
import com.mediacloud.app.newsmodule.utils.KillMusicUtils;
import com.mediacloud.app.newsmodule.utils.VideoAddressGet;
import com.mediacloud.app.reslib.enums.AppFactoryGlobalConfig;
import com.tencent.liteav.demo.superplayer.SuperPlayerView;
import com.tencent.liteav.demo.superplayer.model.entity.VideoSimpleDtos;
import com.tencent.liteav.demo.superplayer.ui.player.FullScreenPlayer;
import com.tencent.liteav.demo.superplayer.ui.videoPlay.VideoPlayObj;
import com.tencent.liteav.demo.superplayer.ui.videoPlay.VideoPlayer;
import com.tencent.liteav.demo.superplayer.ui.videoPlay.VideoPlayerListenerImpl;

import org.jetbrains.annotations.Nullable;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.List;


/**
 * 基于腾讯超级播放器封装的播放器帮助类
 */
@SuppressWarnings("ALL")
public class TxPlayerUtil {

    private Context context;
    private VideoPlayer mPlayer;
    private Object mark = System.currentTimeMillis();
    private RelativeLayout container;
    private View rootView;
    public View mengban;
    private DramaDetailActivity.OnTVCompleteListener mListener;
    public boolean isFull = false;

    public TxPlayerUtil(Context context, DramaDetailActivity.OnTVCompleteListener listener) {
        this.context = context;
        this.mListener = listener;
        initPlayer();
        setVideoPlayerListener();
    }

    private void initPlayer() {
        mPlayer = new VideoPlayer(context);
        mPlayer.setNonWifiTipsMainColor(AppFactoryGlobalConfig.getAppServerConfigInfo(context).getMainColor());
        mPlayer.fullScreenAdd2WindowContentLayer = true;
        mPlayer.setDamuEnable(false);
        mPlayer.stop();
        mPlayer.setAutoPlay(true);
        mPlayer.toggleFullScreenEnable(true);
        mPlayer.displayMore(false);//隐藏掉更多那三个点点
//        mBaiduPlayer.showTogglePlayBtn(View.GONE);
        mPlayer.setvideoQualityTitleViseble(View.VISIBLE);
    }


    /**
     * 设置播放器的容器
     *
     * @param container 播放器的容器
     */
    public void setPlayerContainer(RelativeLayout container/*, View view*/) {
//        if (this.mengban != null && this.mengban != view) this.mengban.setVisibility(View.VISIBLE);
//        this.mengban = view;
        if (mPlayer == null)
            return;
        mPlayer.stop(true);
        this.container = container;
        if (mPlayer.getParent() != null) {
            RelativeLayout rl = (RelativeLayout) mPlayer.getParent();
            rl.removeView(mPlayer);
        }

        this.container.addView(mPlayer, params);
    }

    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);

    /**
     * 释放资源，移除父布局
     */
    public void stopPlay() {
        if (mPlayer != null)
            mPlayer.stop(true);
        if (mPlayer != null && mPlayer.getParent() != null) {
            ViewGroup rl = (ViewGroup) mPlayer.getParent();
            rl.removeView(mPlayer);
        }
    }

    public void pausePlay() {
        if (mPlayer != null) {
            mPlayer.pause();
        }
    }

    public void resumePlay() {
        if (mPlayer != null) {
            mPlayer.onResume();
        }
    }


    public void setVideoData(JSONObject video) {
        KillMusicUtils.stopAPS(context);
        if (video != null) {
            mPlayer.stop();
            mPlayer.setErrorViewVisible(View.GONE);
            try {
                String poster = video.optString("poster", "");
                mPlayer.setPoster(poster);
                JSONArray tsAddress = VideoAddressGet.getAddress(video);
                VideoPlayObj videoPlayObj = new VideoPlayObj();
                String cdnEncypt = video.optString("cdnConfigEncrypt");
                videoPlayObj.setCdn_iv(AppFactoryGlobalConfig.ServerAppConfigInfo.OtherConfig.vms_cdn_iv);
                videoPlayObj.setCdn_key(AppFactoryGlobalConfig.ServerAppConfigInfo.OtherConfig.vms_cdn_key);
                videoPlayObj.setTitle("");
                videoPlayObj.setVID("");
                for (int i = 0; i < tsAddress.length(); i++) {
                    JSONObject line = tsAddress.optJSONObject(i);
                    VideoPlayObj.VideoLineItem lineItem = new VideoPlayObj.VideoLineItem();
                    lineItem.setAddress(line.optString("url"));
                    lineItem.setQuality(line.optString("title"));
                    lineItem.setCdnEncypt(cdnEncypt);
                    videoPlayObj.getMediaItem().add(lineItem);
                }
                mPlayer.getMediaObjs().clear();
                mPlayer.addMediaObjs(videoPlayObj);
                if (videoPlayObj.getMediaItem().size() > 0) {
                    mPlayer.showLoadingView();
                    mPlayer.playVideobj(0);
                }
            } catch (Exception e) {
                e.printStackTrace();
                mPlayer.setErrorViewVisible(View.VISIBLE);
            }
        } else {
            mPlayer.setErrorViewVisible(View.VISIBLE);
        }
    }

    /**
     * 设置播放器各种监听
     */
    private void setVideoPlayerListener() {
        mPlayer.setPlayerViewCallback(new SuperPlayerView.OnSuperPlayerViewCallback() {
            @Override
            public void onStartFullScreenPlay() {
                isFull = true;
            }

            @Override
            public void onStopFullScreenPlay() {
                isFull = false;
            }

            @Override
            public void onClickFloatCloseBtn() {

            }

            @Override
            public void onClickSmallReturnBtn() {
                ((Activity) context).finish();
            }

            @Override
            public void onStartFloatWindowPlay() {

            }

            @Override
            public void onDlnaDeviceListener(String playUrl) {
                if(txPlayOnClickListener!=null){
                    txPlayOnClickListener.onDlnaDeviceListener(playUrl);
                }

            }

            @Override
            public void onSetUpListener() {
                if(txPlayOnClickListener!=null){
                    txPlayOnClickListener.onSetUpListener();
                }
            }
        });

        mPlayer.setOnPlayerListener(new VideoPlayerListenerImpl() {
            @Override
            public void onpause(int currentMediaIndex) {
                super.onpause(currentMediaIndex);

            }

            @Override
            public void oncomplete(int currentMediaIndex) {
                super.oncomplete(currentMediaIndex);
                mListener.onComplete();
                mPlayer.showLoadingView();
                /*mPlayer.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        stopPlay();
                    }
                }, 800);*/
            }

            @Override
            public void ontoggleFullScreen(int currentMediaIndex, boolean isFullScreen) {
                super.ontoggleFullScreen(currentMediaIndex, isFullScreen);
            }

            @Override
            public void onPrepared(int currentMediaIndex) {
                super.onPrepared(currentMediaIndex);
                mPlayer.hideLoadingView();
            }
        });

    }

    public void onDestroy() {
        if (mPlayer != null) {
            mPlayer.stop(true);
            mPlayer.release();
            mPlayer = null;
        }
    }

    public VideoPlayer getPlayer() {
        return mPlayer;
    }


    public void setVideoData(@Nullable DramaDetailResponse.DramaDetailBean.SeriesDtoBean.ProgramListBean programListBean) {
        setVideoData(programListBean, false);
    }

    public void setVideoData(@Nullable DramaDetailResponse.DramaDetailBean.SeriesDtoBean.ProgramListBean programListBean, boolean isLast) {
        KillMusicUtils.stopAPS(context);
        if (mPlayer == null) {
            initPlayer();
        }
        mPlayer.stop();
        mPlayer.setErrorViewVisible(View.GONE);
        mPlayer.setPoster(programListBean.logo);
        //全屏自动加载下一个视频的时候，如果已经是最后一个了，播放完成后则显示重播，不然则显示加载条
        if (isLast) {
            setIsShowReplay(true);
        } else {
            setIsShowReplay(false);
        }
        VideoPlayObj videoPlayObj = new VideoPlayObj();
        videoPlayObj.setTitle(programListBean.name);
        videoPlayObj.setVID("");
        for (int i = 0; i < programListBean.movieList.size(); i++) {
            DramaDetailResponse.DramaDetailBean.SeriesDtoBean.ProgramListBean.MovieListBean movieListBean = programListBean.movieList.get(i);
            VideoPlayObj.VideoLineItem lineItem = new VideoPlayObj.VideoLineItem();

            String playUrl = movieListBean.fileUrl;
            //防盗链
            if (!TextUtils.isEmpty(movieListBean.cdnConfigEncrypt)) {
                playUrl = URLAuth.encode(
                        URLAuth.EncrptMode(
                                movieListBean.cdnConfigEncrypt,
                                AppFactoryGlobalConfig.ServerAppConfigInfo.OtherConfig.vms_cdn_key,
                                AppFactoryGlobalConfig.ServerAppConfigInfo.OtherConfig.vms_cdn_iv),
                        playUrl, false, false);
                Log.e("encodedUrl", playUrl);

            }

            lineItem.setAddress(playUrl);
            lineItem.setQuality(setName(movieListBean.mediaMode));
            videoPlayObj.getMediaItem().add(lineItem);

        }

        mPlayer.showVideoTitleInfo(programListBean.name);
        mPlayer.getMediaObjs().clear();
        mPlayer.addMediaObjs(videoPlayObj);
        if (videoPlayObj.getMediaItem().size() > 0) {
            mPlayer.showLoadingView();
            mPlayer.playVideobj(0);
        }

    }


    public void setVideoData(@Nullable ChildDto programSimpleBean) {
        setVideoData(programSimpleBean, false);
    }

    public void setVideoData(@Nullable ChildDto programSimpleBean, boolean isLast) {
        KillMusicUtils.stopAPS(context);
        if (mPlayer == null) {
            initPlayer();
        }
        mPlayer.stop();
        mPlayer.setErrorViewVisible(View.GONE);
        mPlayer.setPoster(programSimpleBean.getLogo());
        //全屏自动加载下一个视频的时候，如果已经是最后一个了，播放完成后则显示重播，不然则显示加载条
        if (isLast) {
            setIsShowReplay(true);
        } else {
            setIsShowReplay(false);
        }
        VideoPlayObj videoPlayObj = new VideoPlayObj();
        videoPlayObj.setTitle(programSimpleBean.getTitle());
        videoPlayObj.setVID("");
        if (programSimpleBean.getVideoSimpleDtos() != null && programSimpleBean.getVideoSimpleDtos().get(0) != null
         && programSimpleBean.getVideoSimpleDtos().get(0).getFormats()!= null)
        for (int i = 0; i < programSimpleBean.getVideoSimpleDtos().get(0).getFormats().size(); i++) {
            MovieBeannew movieListBean = programSimpleBean.getVideoSimpleDtos().get(0).getFormats().get(i);
            VideoPlayObj.VideoLineItem lineItem = new VideoPlayObj.VideoLineItem();
            String playUrl = movieListBean.getUrl();
            //防盗链 新接口没有该字段，暂时屏蔽
//            if (!TextUtils.isEmpty(movieListBean.getCdnConfigEncrypt())) {
//                playUrl = URLAuth.encode(
//                        URLAuth.EncrptMode(
//                                movieListBean.getCdnConfigEncrypt(),
//                                AppFactoryGlobalConfig.ServerAppConfigInfo.OtherConfig.vms_cdn_key,
//                                AppFactoryGlobalConfig.ServerAppConfigInfo.OtherConfig.vms_cdn_iv),
//                        playUrl, false, false);
//                Log.e("encodedUrl", playUrl);
//
//            }

            lineItem.setAddress(playUrl);
            lineItem.setQuality(movieListBean.getTitle());
            videoPlayObj.getMediaItem().add(lineItem);

        }

        mPlayer.showVideoTitleInfo(programSimpleBean.getTitle());
        mPlayer.getMediaObjs().clear();
        mPlayer.addMediaObjs(videoPlayObj);
        if (videoPlayObj.getMediaItem().size() > 0) {
            mPlayer.showLoadingView();
            mPlayer.playVideobj(0);
        }

    }


    public void setFullPlayMode() {
        if (mPlayer != null) {
            mPlayer.setFullScreen(false);
            mPlayer.setFullScreen(true);
        }
    }
    public void setWinowPlayMode(){
        if(mPlayer!=null){
            mPlayer.setFullScreen(false);
        }
    }


    public void setChooseBtnVisibility(int visibility) {
        if (mPlayer != null) {
            mPlayer.setChooseVisibility(visibility);
        }
    }

    public void setVideosStr(String videosStr, Boolean isTv) {
        if (mPlayer != null) {
            mPlayer.setVideosString(videosStr, isTv);
        }
    }
    public void setChooseCallback(FullScreenPlayer.ChooseCallback callback) {
        if (mPlayer != null) {
            mPlayer.setChooseCallback(callback);
        }
    }
    public void noticeChoosePos(int position) {
        if (mPlayer != null) {
            mPlayer.noticeChoosePos(position);
        }
    }




    public void setSeriesDto(List<ChildDto> programSimpleBean, Boolean isContinuousFlag){
        if(mPlayer!=null){
          mPlayer.setSeriesDto(programSimpleBean,isContinuousFlag);
        }
    }

    public void setSeriesCallBack(FullScreenPlayer.SeriesCallBack callBack){
        if(mPlayer!=null){
            mPlayer.setSeriesCallBack(callBack);
        }
    }


    public void setLoadNextLogo(String logo) {

        if (mPlayer != null) {
            mPlayer.setFullBackground(logo);
        }
    }

    public void setIsShowReplay(boolean isShowReplay) {
        if (mPlayer != null) {
            mPlayer.setIsShowReplay(isShowReplay);
        }
    }

    private String setName(int mediaMode) {
        String name = "";
        switch (mediaMode) {
            case 1:
                name = "流畅";
                break;
            case 2:
                name = "标清";
                break;
            case 3:
                name = "高清";
                break;
            case 4:
                name = "超清";
                break;
            case 5:
                name = "4K";
                break;
            default:
                name = "标清";
                break;
        }
        return name;
    }

    public void setTxPlayOnClickListener(TxPlayOnClick txPlayOnClickListener) {
        this.txPlayOnClickListener = txPlayOnClickListener;
    }

    public TxPlayOnClick txPlayOnClickListener;

   public interface TxPlayOnClick{
       /**
        * 投屏回调
        *
        */
       void onDlnaDeviceListener(String playUrl);

       /**
        * 设置点击回调
        */
       void onSetUpListener();
   }
}